//
//  QNTipsUtil.h
//  QNReuseTool
//
//  Created by rsh on 2019/11/16.
//  Copyright © 2019年 rsh. All rights reserved.
//

#import "QNTipsUtil.h"
#import <MBProgressHUD/MBProgressHUD.h>

typedef NS_ENUM(NSUInteger, QNTipsType) {
    QNTipsTypeText,
    QNTipsTypeInfo,
    QNTipsTypeSuccess,
    QNTipsTypeFaile,
    QNTipsTypeProgress,
    QNTipsTypeStatus
};

@implementation QNTipsUtil

#pragma mark - 通用提示
/**
 常用提示语
 
 @param type 通用提示语类型
 */
+ (void)showNormalTips:(NormalTips)type
{
    if (type < 100) {
        [self showHUDWithMessage:[self messageWithType:type]];
    }else{
        [self showTips:[self messageWithType:type]];
    }
}

+ (NSString *)messageWithType:(NormalTips)type
{
    NSString *tips;
    switch (type) {
        case NormalTipsLoading:
            tips = @"正在加载";
            break;
        case NormalTipsSending:
            tips = @"正在发送";
            break;
        case NormalTipsConnecting:
            tips = @"正在连接";
            break;
        case NormalTipsLogining:
            tips = @"正在登录";
            break;
        case NormalTipsNetworkTimeout:
            tips = @"网络异常";
            break;
        case NormalTipsNetworkUnusual:
            tips = @"连接超时";
            break;
        case NormalTipsRequestFailed:
            tips = @"请求失败";
            break;
        case NormalTipsOperationSuccess:
            tips = @"操作成功";
            break;
        case NormalTipsDownloadFail:
            tips = @"下载失败";
            break;
        default:
            break;
    }
    return tips;
}

#pragma mark - 提示（带菊花）
/**
 白色背景遮挡内容的菊花（view上，需手动隐藏）
 */
+ (void)showMaskHUDWithMessage:(NSString *)message inView:(UIView *)view
{
    [self hideHUDWithView:view];
    MBProgressHUD *hud = [self createMBProgressHUDviewWithMessage:message inView:view icon:nil yOffset:0];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.minSize = CGSizeMake(100, 100);
}

/**
 菊花（Window上，需手动隐藏）
 */
+ (void)showHUD
{
    [self showHUDWithMessage:nil];
}

/**
 带信息菊花（Window上，需手动隐藏）
 
 @param message 提示信息
 */
+ (void)showHUDWithMessage:(NSString *)message
{
    [self showHUDWithMessage:message inView:nil];
}

/**
 带信息菊花（View上，需手动隐藏）
 
 @param message 提示信息
 @param view 显示提示的View
 */
+ (void)showHUDWithMessage:(NSString *)message inView:(UIView *)view
{
    [self showHUDWithMessage:message inView:view delay:0];
}

/**
 带信息菊花（View上，自动隐藏）
 
 @param message 提示信息
 @param view 显示提示的View
 @param time 自动隐藏延迟时间
 */
+ (void)showHUDWithMessage:(NSString *)message inView:(UIView *)view delay:(NSTimeInterval)time
{
    [self hideHUDWithView:view];
    [UIActivityIndicatorView appearanceWhenContainedInInstancesOfClasses:@[MBProgressHUD.class]].color = UIColor.whiteColor;
    MBProgressHUD *hud = [self createMBProgressHUDviewWithMessage:message inView:view icon:nil yOffset:0];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.minSize = CGSizeMake(100, 100);
    if (time > 0) {
        [hud hideAnimated:YES afterDelay:time];
        if (view) {
            hud.completionBlock = ^{
                [[QNHUDHelp share].hudViews removeObject:view];
            };
        }
    }
}

#pragma mark - 提示（不带菊花）

/**
 提示（Window上，1.5s后自动隐藏）
 
 @param message 提示信息
 */
+ (void)showTips:(NSString *)message
{
    [self showTips:message inView:nil];
}

/**
 提示（Window上，显示在底部，1.5s后自动隐藏）
 
 @param message 提示信息
 */
#define screenH [UIScreen mainScreen].bounds.size.height
+ (void)showBottomTips:(NSString *)message
{
    [self hideHUD];
    [self showTips:message inView:nil delay:1.5 yOffset:screenH/2-80];
}

/**
 提示（View上，1.5s后自动隐藏）
 
 @param message 提示信息
 @param view 显示提示的View
 */
+ (void)showTips:(NSString *)message inView:(UIView *)view
{
    [self showTips:message inView:view delay:1.5];
}

/**
 提示（View上，自动隐藏）
 
 @param message 提示信息
 @param view 显示提示的View
 @param time 自动隐藏时间
 */
+ (void)showTips:(NSString *)message inView:(UIView *)view delay:(NSTimeInterval)time
{
    [self showTips:message inView:view delay:time yOffset:0];
}

/**
 提示（View上，自动隐藏）
 
 @param message 提示信息
 @param view 显示提示的View
 @param time 自动隐藏时间
 @param yOffset 距离中心点的Y轴的位置
 */
+ (void)showTips:(NSString *)message inView:(UIView *)view delay:(NSTimeInterval)time yOffset:(CGFloat)yOffset
{
    [self hideHUDWithView:view];
    MBProgressHUD *hud = [self createMBProgressHUDviewWithMessage:message inView:view icon:nil yOffset:yOffset];
    hud.mode = MBProgressHUDModeText;
    if (time > 0) {
        [hud hideAnimated:YES afterDelay:time];
        if (view) {
            hud.completionBlock = ^{
                [[QNHUDHelp share].hudViews removeObject:view];
            };
        }
    }
}

#pragma mark - 成功，失败
/**
 成功提示（View上，自动隐藏）
 
 @param message 提示信息
 */
+ (void)showSuccessWithTips:(NSString *)message
{
    [self hideHUD];
    MBProgressHUD *hud = [self createMBProgressHUDviewWithMessage:message inView:nil icon:@"wanc" yOffset:0];
    hud.mode = MBProgressHUDModeCustomView;
    hud.minSize = CGSizeMake(100, 100);
    [hud hideAnimated:YES afterDelay:1.5];
}

/**
 成功提示（View上，自动隐藏）
 
 @param message 提示信息
 @param time 自动隐藏时间
 */
+ (void)showSuccessWithTips:(NSString *)message delay:(NSTimeInterval)time
{
    [self hideHUD];
    MBProgressHUD *hud = [self createMBProgressHUDviewWithMessage:message inView:nil icon:@"wanc" yOffset:0];
    hud.mode = MBProgressHUDModeCustomView;
    hud.minSize = CGSizeMake(100, 100);
    if (time>0) {
        [hud hideAnimated:YES afterDelay:time];
    }
}

/**
 错误提示（View上，自动隐藏）
 
 @param message 提示信息
 */
+ (void)showErrorWithTips:(NSString *)message
{
    [self hideHUD];
    MBProgressHUD *hud = [self createMBProgressHUDviewWithMessage:message inView:nil icon:@"common_btn_product_share" yOffset:0];
    hud.mode = MBProgressHUDModeCustomView;
    hud.minSize = CGSizeMake(100, 100);
    [hud hideAnimated:YES afterDelay:1.5];
}

/**
 错误提示（View上，自动隐藏）
 
 @param message 提示信息
 @param time 自动隐藏时间
 */
+ (void)showErrorWithTips:(NSString *)message delay:(NSTimeInterval)time
{
    [self hideHUD];
    MBProgressHUD *hud = [self createMBProgressHUDviewWithMessage:message inView:nil icon:@"common_btn_product_share" yOffset:0];
    hud.mode = MBProgressHUDModeCustomView;
    hud.minSize = CGSizeMake(100, 100);
    if (time>0) {
        [hud hideAnimated:YES afterDelay:time];;
    }
}

+ (void)showProgress:(CGFloat)progress message:(NSString *)message
{
    [self showProgress:progress message:message inView:nil];
}

static MBProgressHUD *_hud = nil;
+ (void)showProgress:(CGFloat)progress message:(NSString *)message inView:(UIView *)view
{
    // 多用于网络请求，子线程会crash
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_hud == nil) {
            _hud = [self createMBProgressHUDviewWithMessage:message inView:view icon:nil yOffset:0];
            _hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
            _hud.userInteractionEnabled = YES;
            _hud.bezelView.layer.cornerRadius = 3;
            _hud.bezelView.layer.masksToBounds = YES;
        }
        _hud.label.text = message;
        _hud.progress = progress;
    });
}

+ (void)showActivityWithColor:(UIColor *)color inView:(UIView *)view
{
    [self hideHUD];
    [UIActivityIndicatorView appearanceWhenContainedInInstancesOfClasses:@[MBProgressHUD.class]].color = color ? : UIColor.whiteColor;
    MBProgressHUD *hud = [self createMBProgressHUDviewWithMessage:nil inView:view icon:nil yOffset:0];
    
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = UIColor.clearColor;
    hud.userInteractionEnabled = YES;
}

#pragma mark - 隐藏
/**
 隐藏
 */
+ (void)hideHUD
{
    UIView *winView = (UIView*)[UIApplication sharedApplication].delegate.window;
    [MBProgressHUD hideHUDForView:winView animated:YES];
    for (UIView *view in [QNHUDHelp share].hudViews) {
        [MBProgressHUD hideHUDForView:view animated:YES];
    }
    [[QNHUDHelp share].hudViews removeAllObjects];
    _hud = nil;
}

/**
 隐藏
 
 @param view 所在View
 */
+ (void)hideHUDWithView:(UIView *)view
{
    if (!view) {
        [QNTipsUtil hideHUD];
    }
    else {
        if ([[UIApplication sharedApplication].delegate.window isEqual:view]) {
            [MBProgressHUD hideHUDForView:view animated:YES];
        }
        else {
            [self hideHUD];
        }
        _hud = nil;
        [UIActivityIndicatorView appearanceWhenContainedInInstancesOfClasses:@[MBProgressHUD.class]].color = UIColor.whiteColor;
    }
}

/**
 初始化Hud
 
 @param message 提示语
 @param view 显示提示的View
 @return Hud
 */
+ (MBProgressHUD *)createMBProgressHUDviewWithMessage:(NSString*)message inView:(UIView *)view icon:(NSString *)icon yOffset:(CGFloat)yOffset
{
    if (!view) {
        view = [UIApplication sharedApplication].delegate.window;
    } else {
        [[QNHUDHelp share].hudViews addObject:view];
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.label.text = message ? message : nil;
    hud.label.font = [UIFont boldSystemFontOfSize:15];
    hud.label.numberOfLines = 0;
    hud.margin = 15;
    hud.minShowTime = 0.25;
    hud.contentColor = [UIColor whiteColor];
    hud.bezelView.layer.cornerRadius = 3;
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = [UIColor colorWithRed:17/255.0 green:17/255.0 blue:17/255.0 alpha:0.7];
    hud.removeFromSuperViewOnHide = YES;
    hud.userInteractionEnabled = NO;
    hud.animationType = MBProgressHUDAnimationZoom;
    
    UIImage *img = [QNTipsUtil tp_imgWithCls:[self class] podName:@"QNReuseTool" imgName:icon];
    if (icon) hud.customView = [[UIImageView alloc] initWithImage:img];
    if (yOffset > 0) {
        hud.offset = CGPointMake(0, yOffset);
    }
    
    return hud;
}


/**
 读取私有库中图片资源
 
 @param cls 私有库中Class类名, 这个class不能是Category的class
 @param podName 私有库名称 s.name
 @param imgName 图片名称
 @return 图片
 */
+ (UIImage *)tp_imgWithCls:(Class)cls podName:(NSString *)podName imgName:(NSString *)imgName{
    
    if (!cls || podName.length <= 0 || imgName.length <= 0) {
        return nil;
    }
    
    Class targetCls = cls;
    //    NSClassFromString(className);
    // 源码所在的bundle
    NSBundle *clsBundle = [NSBundle bundleForClass:targetCls];
    NSLog(@"clsBundle = %@ \t\n",clsBundle);
    if (!clsBundle) {
        return nil;
    }
    // 资源所在的bundle路径
    NSURL *resUrl = [clsBundle URLForResource:podName withExtension:@"bundle"];
    if (!resUrl) {
        return nil;
    }
    NSBundle *resBundle = [NSBundle bundleWithURL:resUrl];
    NSLog(@"resBundle = %@ \t\n",resBundle);
    if (!resBundle.loaded) {
        [resBundle load];
    }
    UIImage *retImg = [UIImage imageNamed:imgName inBundle:resBundle compatibleWithTraitCollection:nil];
    
    return retImg;
}


// 获取当前屏幕显示的viewcontroller
+ (UIViewController *)getCurrentWindowVC
{
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal){
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tempWindow in windows){
            if (tempWindow.windowLevel == UIWindowLevelNormal){
                window = tempWindow;
                break;
            }
        }
    }
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]){
        result = nextResponder;
    }
    else{
        result = window.rootViewController;
    }
    return  result;
}

+ (UIViewController *)getCurrentUIVC
{
    UIViewController  *superVC = [[self class]  getCurrentWindowVC];
    if ([superVC isKindOfClass:[UITabBarController class]]) {
        UIViewController  *tabSelectVC = ((UITabBarController*)superVC).selectedViewController;
        if ([tabSelectVC isKindOfClass:[UINavigationController class]]){
            return ((UINavigationController*)tabSelectVC).viewControllers.lastObject;
        }
        return tabSelectVC;
    } else if ([superVC isKindOfClass:[UINavigationController class]]){
        return ((UINavigationController*)superVC).viewControllers.lastObject;
    }
    return superVC;
}
@end

@implementation QNHUDHelp

static QNHUDHelp *hudHelp = nil;

+ (QNHUDHelp *)share
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        hudHelp = [[self alloc] init];
    });
    return hudHelp;
}

- (NSMutableArray *)hudViews
{
    if (!_hudViews) {
        _hudViews = [NSMutableArray array];
    }
    return _hudViews;
}


@end
